package controller


import (

  "fmt"

  "httpserver/utils/metrics"

  "math/rand"

  "net/http"

  "time"

)


func registerImagesRoutes() {

  http.HandleFunc("/images", handleImages)

}


// 添加 0-2 秒的随机延时

func handleImages(w http.ResponseWriter, r *http.Request) {

  timer := metrics.NewTimer()

  defer timer.ObserveTotal()

  randInt := rand.Intn(2000)

  time.Sleep(time.Millisecond * time.Duration(randInt))

  w.Write([]byte(fmt.Sprintf("<h1>%d<h1>", randInt)))

}
package controller


// RegisterRoutes ...

func RegisterRoutes() {

  registerImagesRoutes()

}

func main() {
	http.HandleFunc("/health", healthz)
	http.HandleFunc("/", HandlerNow)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal(err)
	}
}

func healthz(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "这个应用是健康的")
}

func HandlerNow(w http.ResponseWriter, r *http.Request) {
	//接收客户端的request
	for key, val := range r.Header {
		for _, value := range val {
			w.Header().Add(key, value)
			fmt.Fprintf(w, "%s : %s\n", key, r.Header[key])
		}
	}
	version := os.Getenv("VERSION")
	//记录访问日志
	ip := r.RemoteAddr
	Code := http.StatusOK
	log.Printf("IP:%s , Code:%d\n", ip, Code)

	//设置响应码状态:
	w.WriteHeader(Code)
	w.Header().Set("server", version)
}
